package com.breezelin.freshmarket.fragments;

/**
 * Created by Breeze Lin
 * 2016/5/6 07:29
 * 1linyufeng1@gmail.com
 */

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;

import com.breezelin.fmlib.utils.TextUtils;
import com.breezelin.freshmarket.R;
import com.breezelin.freshmarket.activities.SearchActivity;
import com.breezelin.freshmarket.adpaters.HotWordAdapter;
import com.breezelin.freshmarket.app.BaseFragment;
import com.breezelin.freshmarket.network.TaskCanceler;
import com.breezelin.freshmarket.network.asynctasks.HotWordTask;

import java.util.LinkedList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * 《p/>
 * 商品搜索页
 */
public class SearchFragment extends BaseFragment implements View.OnClickListener, HotWordAdapter.HotWordListener {

	/**
	 * 内容编辑框
	 */
	private EditText editText;
	/**
	 * 搜索热词适配器
	 */
	private HotWordAdapter adapter;
	/**
	 * 搜索热词集合
	 */
	private List<String> hotWords;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                         Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_search, container, false);
		initData();
		bindViews();
		getHotWords();
		return rootView;
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		hotWords = new LinkedList<>();
	}

	/**
	 * 绑定视图
	 */
	private void bindViews() {
		// 绑定视图
		editText = (EditText) rootView.findViewById(R.id.edit);
		Button button = (Button) rootView.findViewById(R.id.btn);
		GridView hotWordGrid = (GridView) rootView.findViewById(R.id.list);
		adapter = new HotWordAdapter(getActivity(), hotWords, this);
		hotWordGrid.setAdapter(adapter);

		// 设置监听
		button.setOnClickListener(this);
	}

	/**
	 * 获取搜索热词
	 */
	private void getHotWords() {
		new HotWordTask() {
			@Override
			protected void onSuccess(List<String> strings) {
				// 填充热词数据，刷新列表
				hotWords.addAll(strings);
				adapter.notifyDataSetChanged();
			}
		}.execute();
	}

	/**
	 * 进行搜索
	 *
	 * @param string 搜索词汇
	 */
	private void search(String string) {
		// 若搜索内容存在，传入搜索页面进行搜索的执行
		if (!TextUtils.isEmpty(string)) {
			Intent intent = new Intent(getActivity(), SearchActivity.class);
			intent.putExtra("string", string);
			startActivity(intent);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		TaskCanceler.cancelHotWordRequests();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn:
				// 取出当前编辑的文本
				Editable text = editText.getText();
				String string = text.toString();
				// 进行搜索
				search(string);
				// 置空输入
				editText.setText("");
				break;
		}
	}

	@Override
	public void onHotWordClick(String hotWord) {
		// 热词点击，进行搜索
		search(hotWord);
	}
}
